<template>
  <div class="favorites-page">
    <div class="page-header">
      <h2>我的收藏</h2>
      <div class="header-actions">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索收藏内容..."
            prefix-icon="Search"
            clearable
            class="search-input"
        />
        <el-select v-model="sortField" placeholder="排序方式" class="sort-select">
          <el-option label="按时间排序" value="time" />
          <el-option label="按名称排序" value="name" />
        </el-select>
      </div>
    </div>

    <div class="favorites-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>加载中...</span>
      </div>

      <!-- 空状态 -->
      <div v-else-if="filteredFavorites.length === 0" class="empty-state">
        <el-empty description="暂无收藏内容">
          <el-button type="primary" @click="goDiscover">去发现精彩内容</el-button>
        </el-empty>
      </div>

      <!-- 收藏列表 -->
      <div v-else class="favorites-grid">
        <div
            v-for="item in filteredFavorites"
            :key="item.id"
            class="favorite-item"
        >
          <div class="item-image">
            <el-image
                :src="item.thumbnail"
                fit="cover"
                class="thumbnail"
                :preview-src-list="[item.thumbnail]"
            >
              <template #error>
                <div class="image-error">加载失败</div>
              </template>
            </el-image>
            <div class="item-duration" v-if="item.duration">{{ item.duration }}</div>
            <div class="item-actions">
              <el-button
                  circle
                  size="small"
                  class="action-btn"
                  @click="playItem(item)"
              >
                <el-icon><VideoPlay /></el-icon>
              </el-button>
              <el-button
                  circle
                  size="small"
                  class="action-btn unfavorite-btn"
                  @click="removeFavorite(item.id)"
              >
                <el-icon><Star /></el-icon>
              </el-button>
            </div>
          </div>

          <div class="item-info">
            <h4 class="item-title" :title="item.title">{{ item.title }}</h4>
            <p class="item-desc" :title="item.description">{{ item.description }}</p>
            <div class="item-meta">
              <span class="up-name">{{ item.upName }}</span>
              <span class="collect-time">{{ formatTime(item.collectTime) }}</span>
            </div>
            <div class="item-stats">
              <span class="play-count">
                <el-icon><View /></el-icon>
                {{ formatCount(item.playCount) }}
              </span>
              <span class="danmaku-count">
                <el-icon><ChatDotRound /></el-icon>
                {{ formatCount(item.danmakuCount) }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="filteredFavorites.length > 0" class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredFavorites.length"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-show="selectedFavorites.length > 0" class="batch-actions">
      <div class="batch-info">
        已选择 {{ selectedFavorites.length }} 项
      </div>
      <div class="batch-buttons">
        <el-button @click="cancelBatchSelect">取消</el-button>
        <el-button type="danger" @click="batchRemoveFavorites">批量取消收藏</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import {
  Loading,
  VideoPlay,
  Star,
  View,
  ChatDotRound
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const sortField = ref('time')
const currentPage = ref(1)
const pageSize = ref(12)
const selectedFavorites = ref([])

// 模拟收藏数据
const favorites = ref([
  {
    id: 1,
    title: 'Vue3 + Element Plus 实战教程：从零开始构建现代化前端项目',
    description: '完整的Vue3和Element Plus实战教学，包含最新特性使用',
    thumbnail: 'https://example.com/thumb1.jpg',
    duration: '15:30',
    upName: '前端开发实验室',
    playCount: 125000,
    danmakuCount: 3500,
    collectTime: '2024-01-15T10:30:00Z'
  },
  {
    id: 2,
    title: 'Element Plus 组件库深度解析',
    description: '深入理解Element Plus组件的使用和原理',
    thumbnail: 'https://example.com/thumb2.jpg',
    duration: '22:45',
    upName: 'UI设计之家',
    playCount: 89000,
    danmakuCount: 2100,
    collectTime: '2024-01-14T16:20:00Z'
  }
])

// 计算属性
const filteredFavorites = computed(() => {
  let result = [...favorites.value]

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item =>
        item.title.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword) ||
        item.upName.toLowerCase().includes(keyword)
    )
  }

  // 排序
  result.sort((a, b) => {
    if (sortField.value === 'time') {
      return new Date(b.collectTime) - new Date(a.collectTime)
    } else {
      return a.title.localeCompare(b.title)
    }
  })

  return result
})
//
// const paginatedFavorites = computed(() => {
//   const start = (currentPage.value - 1) * pageSize.value
//   const end = start + pageSize.value
//   return filteredFavorites.value.slice(start, end)
// })

// 方法
const loadFavorites = async () => {
  loading.value = true
  try {
    const response = await request.get('/video/collect')
    
    if (response.status === 200 && response.data.code === 0) {
      // 处理返回的数据
      if (Array.isArray(response.data.data)) {
        favorites.value = response.data.data.map(item => ({
          id: item.id || item.videoId,
          title: item.title || item.videoTitle || '未知标题',
          description: item.description || item.videoDescription || '',
          thumbnail: item.thumbnail || item.cover || item.videoCover || '',
          duration: item.duration || '',
          upName: item.upName || item.authorName || '未知UP主',
          playCount: item.playCount || item.views || 0,
          danmakuCount: item.danmakuCount || item.danmaku || 0,
          collectTime: item.collectTime || item.createTime || new Date().toISOString()
        }))
      } else if (response.data.data) {
        // 如果返回的是单个对象，转换为数组
        favorites.value = [response.data.data]
      } else {
        favorites.value = []
      }
    } else {
      ElMessage.error(response.data.message || '加载收藏列表失败')
      favorites.value = []
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    ElMessage.error(error.response?.data?.message || '加载收藏列表失败，请稍后重试')
    favorites.value = []
  } finally {
    loading.value = false
  }
}

const removeFavorite = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const index = favorites.value.findIndex(item => item.id === id)
    if (index !== -1) {
      favorites.value.splice(index, 1)
      ElMessage.success('取消收藏成功')
    }
  } catch (error) {
    // 用户点击取消
  }
}

const batchRemoveFavorites = async () => {
  try {
    await ElMessageBox.confirm(`确定要取消收藏选中的 ${selectedFavorites.value.length} 项内容吗？`, '批量操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    favorites.value = favorites.value.filter(item =>
        !selectedFavorites.value.includes(item.id)
    )
    selectedFavorites.value = []
    ElMessage.success('批量取消收藏成功')
  } catch (error) {
    // 用户点击取消
  }
}

const playItem = (item) => {
  // 跳转到播放页面
  router.push(`/video/${item.id}`)
}

const goDiscover = () => {
  router.push('/discover')
}

const cancelBatchSelect = () => {
  selectedFavorites.value = []
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const formatCount = (count) => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万'
  }
  return count.toString()
}

const formatTime = (timeString) => {
  return new Date(timeString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.favorites-page {
  padding: 30px;
  min-height: 600px;
  width: 100%;
  box-sizing: border-box;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e7e7e7;
}

.page-header h2 {
  margin: 0;
  color: #18191c;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.sort-select {
  width: 120px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999;
}

.loading-icon {
  font-size: 40px;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

@media (min-width: 1200px) {
  .favorites-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (min-width: 900px) and (max-width: 1199px) {
  .favorites-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (min-width: 600px) and (max-width: 899px) {
  .favorites-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.favorite-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.favorite-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.item-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f5f5f5;
  color: #999;
}

.item-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.item-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.favorite-item:hover .item-actions {
  opacity: 1;
}

.action-btn {
  background: rgba(255, 255, 255, 0.9);
  border: none;
}

.unfavorite-btn {
  color: #ff6b6b;
}

.item-info {
  padding: 16px;
}

.item-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #18191c;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-desc {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #61666d;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #999;
}

.up-name {
  color: #00a1d6;
}

.item-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.item-stats .el-icon {
  margin-right: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 12px 24px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 16px;
  z-index: 1000;
}

.batch-info {
  font-size: 14px;
  color: #61666d;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .favorites-page {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: space-between;
  }

  .search-input {
    width: 150px;
  }

  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .batch-actions {
    left: 12px;
    right: 12px;
    transform: none;
    bottom: 12px;
  }
}
</style>